package com.ray.wms.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.common.SysMsgCodeConstant;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.wms.check.OrderAllotCheck;
import com.ray.wms.enums.OrderStatusEnum;
import com.ray.wms.service.WmsOrderAllotService;
import com.ray.wms.service.WmsWarehouseService;
import com.ray.wms.service.compose.AllotService;
import com.ray.wms.table.dto.OrderAllotQueryDTO;
import com.ray.wms.table.dto.OrderStatusChangeDTO;
import com.ray.wms.table.entity.WmsOrderAllot;
import com.ray.wms.table.entity.WmsWarehouse;
import com.ray.wms.table.params.order.OrderAllotQueryParams;
import com.ray.wms.table.vo.order.OrderAllotVO;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 调仓相关服务
 * @Class: InApi
 * @Package com.ray.wms.api
 * @date 2020/6/3 15:09
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
@Service
public class OrderAllotApi {

    @Autowired
    private WmsWarehouseService wmsWarehouseService;
    @Autowired
    private WmsOrderAllotService wmsOrderAllotService;
    @Autowired
    private AllotService allotService;

    /**
     * 查询调仓订单
     * @param queryParams
     * @return
     */
    public Result<IPage<OrderAllotVO>> queryOrderAllots(CommonPage<OrderAllotQueryParams,Page<OrderAllotVO>> queryParams){
        LoginUser loginUser = LogInUserUtil.get();
        Map<String,WmsWarehouse> wmsWarehouseMap = new HashMap<>();
        CommonPageBuilder<OrderAllotQueryDTO,WmsOrderAllot> commonPageBuilder = new CommonPageBuilder<>(OrderAllotQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<WmsOrderAllot> page = wmsOrderAllotService.page(commonPageBuilder.bulid(),loginUser);
        List<WmsOrderAllot> customers = page.getRecords();
        //结果对象
        IPage<OrderAllotVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if(ObjectUtil.isNotNull(customers)){
            pageList.setRecords(customers.stream().map(wmsOrderAllot -> {
                OrderAllotVO orderVO = new OrderAllotVO();
                BeanUtil.copyProperties(wmsOrderAllot,orderVO);
                //查询仓库信息
                WmsWarehouse inWmsWarehouse = wmsWarehouseMap.get(wmsOrderAllot.getInWarehouseCode());
                if(ObjectUtil.isEmpty(inWmsWarehouse)){
                    inWmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(wmsOrderAllot.getInWarehouseCode(),loginUser);
                    wmsWarehouseMap.put(inWmsWarehouse.getWarehouseCode(),inWmsWarehouse);
                }
                orderVO.setInWarehouseName(inWmsWarehouse.getWarehouseName());
                //查询仓库信息
                WmsWarehouse outWmsWarehouse = wmsWarehouseMap.get(wmsOrderAllot.getOutWarehouseCode());
                if(ObjectUtil.isEmpty(outWmsWarehouse)){
                    outWmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(wmsOrderAllot.getOutWarehouseCode(),loginUser);
                    wmsWarehouseMap.put(outWmsWarehouse.getWarehouseCode(),outWmsWarehouse);
                }
                orderVO.setOutWarehouseName(outWmsWarehouse.getWarehouseName());
                return  orderVO;
            }).collect(Collectors.toList()));
        }else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002,pageList);
    }

    /**
     * 调库操作
     * @param orderNo
     * @return
     */
    @Transactional
    public Result<String> doOrder(String orderNo){
        ValidateUtil.hasLength(orderNo,"参数[orderNo]不能为空");
        LoginUser loginUser = LogInUserUtil.get();
        WmsOrderAllot orderAllot = wmsOrderAllotService.queryByOrderNo(orderNo,loginUser);
        new OrderAllotCheck(orderAllot).checkNull(SysMsgCodeConstant.Error.ERR10000002).canDoCheck(SysMsgCodeConstant.Error.ERR10000015);
        //更新订单状态
        OrderStatusChangeDTO orderStatusChangeDTO = new OrderStatusChangeDTO(orderNo, OrderStatusEnum.DO.getValue(),orderAllot.getUpdateVersion());
        if(!wmsOrderAllotService.updateStatus(orderStatusChangeDTO,loginUser)){
            log.info("更新订单状态异常,参数：{}", JSON.toJSONString(orderStatusChangeDTO));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //处理操作
        allotService.orderAllot(orderAllot,loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,orderNo);
    }



}
